﻿using Loogn.OrmLite;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskCaller.Models;
using TaskCaller.Models.entity;
using TaskCaller.Repositories;

namespace TaskCaller.Services
{
    public class ExecuteLogService
    {
        private readonly IExecuteLogRepository _executeLogRepository;
        private readonly CallerServerConfig _callerServerConfig;
        public ExecuteLogService(IExecuteLogRepository executeLogRepository, IOptions<CallerServerConfig> options)
        {
            _executeLogRepository = executeLogRepository;
            _callerServerConfig = options.Value;
        }

        public long Add(ExecuteLog m)
        {
            m.AddTime = DateTime.Now;
            Console.WriteLine("TaskId:{0},Type:{1},Name:{2},Method:{3},Url:{4},Data:{5},Status:{6},Message:{7},Time:{8}",
                m.TaskId, m.TaskType == 1 ? "定时" : "延迟", m.TaskName, m.TaskMethod, m.TaskUrl, m.PostData, m.GetStatus(), m.Message, m.AddTime.ToString("yyyy-MM-dd HH:mm:ss"));
            if (m.Status != 1 || _callerServerConfig.RecordSuccessLog)
            {
                return _executeLogRepository.Add(m);
            }
            else
            {
                return 0;
            }
        }

        public OrmLitePageResult<ExecuteLog> SearchList(long taskId, int taskType, int status, int pageIndex, int pageSize)
        {
            return _executeLogRepository.SearchList(taskId, taskType, status, pageIndex, pageSize);
        }
    }
}
